package com.itcms.core.web.fore;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itcms.common.util.DateUtil;
import com.itcms.core.domain.Info;
import com.itcms.core.domain.InfoDetail;
import com.itcms.core.domain.InfoFile;
import com.itcms.core.domain.InfoImage;
import com.itcms.core.domain.Information;
import com.itcms.core.service.InfoDetailService;
import com.itcms.core.service.InfoService;
import com.itcms.core.service.InformationService;

@Controller
/*@RequestMapping("/console")*/
public class InfoParserController { 
	
	@Autowired
	private InformationService informationService;
	@Autowired
	private InfoService infoService;
	
	@ResponseBody
	@RequestMapping("/parseInfo.htmx")
	public String parseInfo(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="requiredDate",required=false)String requiredDate,
			@RequestParam(value="nodeIds",required=false)String nodeIds) {
		File file = new File("D:\\tmp\\gdjt"); 
		getDriectory(file,request,requiredDate,nodeIds);
		
		return "数据迁移成功！";
	}

	
	/**
	 * 遍历文件夹中的内容
	 * @param file
	 */
	public void getDriectory(File file,HttpServletRequest request,String requiredDate,String nodeIds){
		File files[] = file.listFiles();
		if(files == null || files.length==0){
			return;
		}
		for(File f:files){
			if(f.isDirectory()){
				getDriectory(f,request,requiredDate,nodeIds);
			}else{
				String fileName = f.getName();
				int index = fileName.indexOf(".html");				
				if(index > -1){
					String infoIdStr = fileName.substring(0, index);
					if(!Pattern.compile("(?i)[a-z]").matcher(infoIdStr).find()){
						int infoId = Integer.parseInt(infoIdStr);
						String path = f.getAbsolutePath();
						String parentPath = f.getParent().substring(0, f.getParent().lastIndexOf("\\"));
						parentPath = parentPath.substring(parentPath.lastIndexOf("\\")+1, parentPath.length());
						getInformation(path,infoId,request,requiredDate,nodeIds); 
					}					
				}
				
			}
		}
	}
	
	public void getInformation(String path, int id,HttpServletRequest request,String requiredDate,String nodeIds){
		Information information = informationService.get(id);
		if(!org.springframework.util.StringUtils.isEmpty(information)){
			Date publishedTime = information.getInfoPublishedTime();
			if(!org.springframework.util.StringUtils.isEmpty(requiredDate)){
				if(!org.springframework.util.StringUtils.isEmpty(publishedTime)){
					if(DateUtil.getDateStr(information.getInfoPublishedTime(), "yyyy/MM/dd HH:mm:ss").compareTo(requiredDate) >= 0){
						fileMange(path, information, request,nodeIds);
					}
				}
			}else{
				fileMange(path, information, request,nodeIds);
			}
			
		}
	}
	
	private void fileMange(String path,Information information,HttpServletRequest request, String nodeIds){
		if(information.getInfoStatus() != 9) return;
		String nodeName = path.split("\\\\")[ path.split("\\\\").length-3];
		if(!nodeName.equals(information.getCategory().getCateCode())) return;
		
		try {
			fileManage(path, information,request,nodeIds);
		} catch (IOException e) {
			e.printStackTrace(); 
		}
	}
	
	/**
	 * 获取文档内容
	 * @param path
	 * @param information
	 * @return
	 * @throws IOException
	 */
public void fileManage(String path, Information information,HttpServletRequest request, String nodeIds) throws IOException{
		
		StringBuffer buffer = new StringBuffer();
		String content = "";
		String title="";
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF-8"));
		try {
			
			String lineTxt = "";
			while((lineTxt = bufferedReader.readLine()) != null){
				buffer.append(lineTxt);
			}
			content = buffer.toString();
			/*setImgSrc(content,request);
			setFileURL(content);*/
			
			Pattern pa = Pattern.compile("<title>.*?</title>");
			Matcher ma = pa.matcher(content);
			while(ma.find()){
				title = ma.group().replaceAll("<.*?>", "");
			}
			
			int start = content.indexOf("<p");
			if(start == -1){
				start = content.indexOf("<P");
				if(start == -1){
					content = "";
					return;
				}
			}
			int end = content.lastIndexOf("/p>");
			if(end == -1){
				end = content.lastIndexOf("/P>");
				if(end == -1){
					content = "";
					return;
				}
			}
			
			String nodeIdStr = readCateToNode(information.getCategory().getCateId()).trim();
			
			if(StringUtils.isNotEmpty(nodeIdStr)){
				if(!org.springframework.util.StringUtils.isEmpty(nodeIds)){
					if(!Arrays.asList(nodeIds.split(",")).contains(nodeIdStr))
						return;	
					content = content.substring(start,end);
					content = setFileURL(content);
					content = setImgSrc(content,request);
					saveInfo(information,content,title,Integer.parseInt(nodeIdStr));
				}else{
					content = content.substring(start,end);
					content = setFileURL(content);
					content = setImgSrc(content,request);
					saveInfo(information,content,title,Integer.parseInt(nodeIdStr));
				}
			}else{
				return;
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			bufferedReader.close();
		}
	}
	

	/**
	 * 如果包含图片则更改图片及文档的路径
	 * @param content
	 * @return
	 * @throws IOException
	 */
	public String setImgSrc(String content,HttpServletRequest request) throws IOException{
		Pattern pImage;
		Matcher mImage;
		String regExImg = "<(img|IMG)(.*?)(/>|></(img|IMG)>|>)";
		pImage = Pattern.compile(regExImg,Pattern.CASE_INSENSITIVE);
		mImage = pImage.matcher(content);
		String rootUrl = "http://172.20.1.83:8080/itcms/gdjtoa/";
		content = content.replaceAll("～", "~");
		
		while(mImage.find()){
			String src = mImage.group();
			String subUrl = "uploads/5/";
			String tempUrl = "";
			Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(src);
			 while (m.find()) {
				 String url = m.group(1);
				 if(url.indexOf(rootUrl) == -1){
			   		  if(url.indexOf("ewebeditor/") >= 0){
			   			  tempUrl = rootUrl + subUrl + url.substring(url.indexOf("ewebeditor/"),url.length());
			   			  System.out.println("tempUrl = " + tempUrl);
			   		  }else if(url.indexOf("cmsmedia/") >= 0){
			   			  tempUrl = rootUrl + subUrl + url.substring(url.indexOf("cmsmedia/"),url.length());
			   			  System.out.println("tempUrl = " + tempUrl);
			   		  }else if(url.indexOf("/Attachment/") >= 0){
			   			  if(url.indexOf("http://") == -1)
			   				  tempUrl = rootUrl +  subUrl + url.substring(url.indexOf("Attachment/"),url.length());
			   			  else
			   				  tempUrl = url;
			   			 System.out.println("tempUrl = " + tempUrl);
			   			 System.out.println("url = " + url);
			   		  }else if(url.indexOf("publicfiles/") >= 0){
			   			tempUrl = rootUrl + url.substring(url.indexOf("publicfiles/"),url.length());
			   			System.out.println("url = " + url);
			   			 System.out.println("tempUrl = " + tempUrl);
			   		  }else if(url.indexOf(subUrl) >= 0){
			   			 tempUrl = rootUrl + subUrl + url.substring(url.indexOf("uploads/5/"),url.length());
			   			 System.out.println("tempUrl = " + tempUrl);
				   	  } 
		   			  content = content.replaceAll(url, tempUrl);
				}
			 }
		}
		return content;
		
	}
	
	public String setFileURL(String content){
		String regex="<a.*?/a>";    
        Pattern pt=Pattern.compile(regex);
        Matcher mt=pt.matcher(content);
        String rootUrl = "http://172.20.1.83:8080/itcms/gdjtoa/";
        String subUrl = "uploads/5/";
        String tempUrl = "";
 
        while(mt.find())
        { 
            if(true)
            {
                  while(mt.find())
                  {
                	  String href="href=.*?>";
                	  Pattern hrefPt = Pattern.compile(href);
                	  Matcher hrefMt=hrefPt.matcher(mt.group());
                	  System.out.println("Url = " + mt.group());
                	  while(hrefMt.find()){
                		  String url = hrefMt.group().replaceAll("href=|>","");
                		  if(url.indexOf(rootUrl) == -1){
	                		  if(url.indexOf("ewebeditor/") >= 0){
	                			  tempUrl = rootUrl + subUrl + url.substring(url.indexOf("ewebeditor/"),url.length());
	    			   			 // System.out.println("tempUrl = " + tempUrl);
	    			   		  }else if(url.indexOf("cmsmedia/") >= 0){
	    			   			tempUrl = rootUrl + subUrl + url.substring(url.indexOf("cmsmedia/"),url.length());
	    			   			 // System.out.println("tempUrl = " + tempUrl);
	    			   		  }else if(url.indexOf("/Attachment/") >= 0){
	    			   			tempUrl = rootUrl +  subUrl + url.substring(url.indexOf("Attachment/"),url.length());
	    			   			// System.out.println("tempUrl = " + url);
	    			   		  }else if(url.indexOf("publicfiles/") >= 0){
	    			   			tempUrl = rootUrl + url.substring(url.indexOf("publicfiles/"),url.length());
	    			   			// System.out.println("tempUrl = " + tempUrl);
	    			   		  }else if(url.indexOf(subUrl) >= 0){
	    			   			tempUrl = rootUrl + subUrl + url.substring(url.indexOf("uploads/5/"),url.length());
	    			   			// System.out.println("tempUrl = " + tempUrl);
	    				   	  } 
	                		  content = content.replaceAll(url, tempUrl);
                		  }
                	  }
                  }
                  
            } 
            
        }
        return content;
	}
	
	/*public void setDetailFile(){
		List<InfoDetail> infoDetails = infoDetailService.findAll();
		String rootUrl = "http://172.20.1.83:8080/itcms/gdjtoa/";
		for(InfoDetail detail : infoDetails){
			String smallImage = detail.getSmallImage();
			String largeImage = detail.getLargeImage();
			if(smallImage.length() > 0){
				if(smallImage.indexOf("/itcms") >= 0){
					
				}
			}
			
			if(largeImage.length() > 0){
				
			}
		}
	}
	
	public void setClobUrl(){
		
	}*/
/*	public String setImgSrc(String content,HttpServletRequest request) throws IOException{
		Pattern pImage;
		Matcher mImage;
		String regExImg = "<(img|IMG)(.*?)(/>|></(img|IMG)>|>)";
		pImage = Pattern.compile(regExImg,Pattern.CASE_INSENSITIVE);
		mImage = pImage.matcher(content);
		String image = "";
		String rootUrl = request.getContextPath() + "/uploads/5/image";
		String ewebeditorUrl = rootUrl + "/ewebeditor";
		content = content.replaceAll("http://www.dggdjt.com:9999/ewebeditor","/ewebeditor");
		content = content.replaceAll("HTTP://www.dggdjt.com:9999/ewebeditor","/ewebeditor");
		content = content.replaceAll("/publicfiles/business/htmlfiles/gdjt",rootUrl);
		content = content.replaceAll("/ewebeditor/uploadfile", ewebeditorUrl + "/uploadfile");	
		content = content.replaceAll("/ewebeditor/sysimage", ewebeditorUrl + "/sysimage");
		//content = content.replaceAll("～", "~");
		while(mImage.find()){
			image = mImage.group();
			if(image.indexOf("/Attachment/") > -1) content = content.replaceAll(image, "");
		}
		return content;
		
	}
*/		
	public InfoDetail infoDetail(Information information,String title){
		InfoDetail infoDetail = new InfoDetail();
		if(title.equals("") != true) 
			infoDetail.setTitle(title);			
		else 
			infoDetail.setTitle(information.getInfoTitle());
		infoDetail.setMetaDescription(information.getInfoTitle());
		infoDetail.setStrong(false);
		infoDetail.setSmallImage(information.getSubTitle());
		infoDetail.setEm(false);
		return infoDetail;
	}
	
	/**
	 * 根据文档info_id存到数据库中
	 * @param information
	 * @param content
	 */
	public void saveInfo(Information information, String content,String title, Integer nodeId){
		Info info = new Info();
		
		Map<String, String> customs = new LinkedHashMap<String,String>();
		customs.put("text_editor_type", "ueditor");		
		Map<String, String> clobs = new LinkedHashMap<String,String>();
		clobs.put("text", content);
		Map<String, String> attrImages = new LinkedHashMap<String,String>();
		List<InfoImage> images = new ArrayList<InfoImage>();
		List<InfoFile> files = new ArrayList<InfoFile>();
	
		InfoDetail infoDetail = infoDetail(information,title);
		info.setPublishDate(information.getInfoPublishedTime());
		info.setOffDate(information.getInfoExpiredate());
		
		try{
				
			infoService.save(info, infoDetail, null, null, null, null, customs, clobs, images, files, null, attrImages, null, nodeId, 21, "A", 5);	
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 处理原数据库中的cate_id对应到当前数据库的node_id配置文件
	 * @param cateId
	 * @return
	 */
	public String readCateToNode(int cateId){
		return getString(cateId+""); 
	}
	
	private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
			.getBundle("cateconfig");

	public static String getString(String key) {
		try {
			if(RESOURCE_BUNDLE.containsKey(key)){
				return RESOURCE_BUNDLE.getString(key);
			}			
		} catch (MissingResourceException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public String getBody(String val){
		String start = "<body>";
		String end = "</body>";
		int s = val.indexOf(start) + start.length();
		int e = val.indexOf(end);
		return val.substring(s,e);
	}
}
